# 处理翻译结果广播的模块

# 存储WebSocket连接
# 结构: {meeting_id: {language: [websocket1, websocket2, ...]}}
websocket_connections = {}


# 广播翻译结果到所有连接的WebSocket客户端
async def broadcast_translation(meeting_id: str, language: str, text: str):
    if meeting_id in websocket_connections:
        if language in websocket_connections[meeting_id]:
            for websocket in websocket_connections[meeting_id][language]:
                try:
                    await websocket.send_text(text)
                except Exception as e:
                    print(f"发送消息失败: {e}")
                    # 移除无效连接
                    websocket_connections[meeting_id][language].remove(websocket)


# 广播停止录音通知到所有连接的WebSocket客户端
async def broadcast_recording_stopped(meeting_id: str):
    if meeting_id in websocket_connections:
        for language in websocket_connections[meeting_id]:
            for websocket in websocket_connections[meeting_id][language]:
                try:
                    # 使用特殊格式发送停止录音通知
                    await websocket.send_text("__RECORDING_STOPPED__")
                except Exception as e:
                    print(f"发送停止录音通知失败: {e}")
                    # 移除无效连接
                    websocket_connections[meeting_id][language].remove(websocket)


# 广播程序关闭通知到所有连接的WebSocket客户端
async def broadcast_program_closed(meeting_id: str):
    if meeting_id in websocket_connections:
        for language in websocket_connections[meeting_id]:
            for websocket in websocket_connections[meeting_id][language]:
                try:
                    # 使用特殊格式发送程序关闭通知
                    await websocket.send_text("__PROGRAM_CLOSED__")
                except Exception as e:
                    print(f"发送程序关闭通知失败: {e}")
                    # 移除无效连接
                    websocket_connections[meeting_id][language].remove(websocket)
